package com.rytong.tools.ui.jsfunction;
//#define Android2.2
import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.rytong.tools.ui.LPWebView.MyLPWebView;
import com.rytong.tools.utils.Utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
// #ifdef Android2.2
import android.telephony.cdma.CdmaCellLocation;
// #endif
import android.telephony.gsm.GsmCellLocation;

public class EmpGPS {
    public static double LATITUDE;
    public static double LONGITUDE;
    final String UNKNOWN_ERROR = "1";
    final String NOT_SUPPORT_ERROR = "2";
    final String TIME_OUT_ERROR = "3";
    final String NO_DATA_ERROR = "4";

    public void getCurrentLocation(MyLPWebView ewv, Activity activity, String Callback, double accuracy) {
        String callbackString = "";

        // TODO Auto-generated method stub
        final LocationManager alm = (android.location.LocationManager) activity
                .getSystemService(Context.LOCATION_SERVICE);
        // 判断gps是否开
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            // 查找到服务信号
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            // 高精度
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            // 低功耗
            String provider = alm.getBestProvider(criteria, true);
            // 获取GPS信息
            Location location = alm.getLastKnownLocation(provider);
            // 通过GPS获取位置
            if (location != null) {
                LATITUDE = location.getLatitude();
                LONGITUDE = location.getLongitude();
            } else {
                // 如果没获取到，则用基栈获取定位信息
                location = alm.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER);
                if (location != null) {
                    LATITUDE = location.getLatitude();
                    LONGITUDE = location.getLongitude();
                } else {

                }
            }
        } else {
            int timeoutConnection = 3000;
            int timeoutSocket = 5000;
            TelephonyManager mTelNet = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
            String operator = mTelNet.getNetworkOperator();
            CellLocation cl = mTelNet.getCellLocation();
            // #ifdef Android2.2
            if (cl instanceof CdmaCellLocation) {
                CdmaCellLocation location = (CdmaCellLocation) cl;
                LATITUDE = (double) location.getBaseStationLatitude() / 14400;// 14400即 *90/1296000
                LONGITUDE = (double) location.getBaseStationLongitude() / 14400;

            } else if (null != operator && !operator.equals("")) {
                // #else
//@                if (null != operator && !operator.equals("")) {
                // #endif
                String mcc = operator.substring(0, 3);
                String mnc = operator.substring(3);

                if (cl instanceof GsmCellLocation) {
                    GsmCellLocation location = (GsmCellLocation) cl;
                    if (null != location) {
                        int cid = location.getCid();
                        int lac = location.getLac();
                        HttpParams httpParameters = new BasicHttpParams();
                        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                        HttpClient httpclient = new DefaultHttpClient(httpParameters);
                        HttpPost post = new HttpPost("http://www.google.com/loc/json");
                        try {
                            JSONObject holder = new JSONObject();
                            holder.put("version", "1.1.0");
                            holder.put("host", "maps.google.com");
                            holder.put("address_language", "zh_CN");
                            holder.put("request_address", true);
                            JSONObject tower = new JSONObject();
                            tower.put("mobile_country_code", mcc);
                            tower.put("mobile_network_code", mnc);
                            tower.put("cell_id", cid);
                            tower.put("location_area_code", lac);
                            JSONArray towerarray = new JSONArray();
                            towerarray.put(tower);
                            holder.put("cell_towers", towerarray);
                            StringEntity query = new StringEntity(holder.toString());
                            post.setEntity(query);
                            HttpResponse response = httpclient.execute(post);
                            HttpEntity entity = response.getEntity();
                            BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                            StringBuffer strBuff = new StringBuffer();
                            String result = null;
                            while ((result = buffReader.readLine()) != null) {
                                strBuff.append(result);
                            }
                            JSONObject json = new JSONObject(strBuff.toString());
                            JSONObject subjosn = new JSONObject(json.getString("location"));
                            LATITUDE = Double.parseDouble(subjosn.getString("latitude"));
                            LONGITUDE = Double.parseDouble(subjosn.getString("longitude"));
                        } catch (Exception e) {
                            // LPUtils.printException(e);
                            Utils.printException(e);
                            // callbackString = "javascript:".concat(failCallback).concat("(").concat(e.toString())
                            // .concat(")");
                            ewv.loadUrl(callbackString);
                        }
                    }
                }
            }

        }

        LocationListener llistener = new LocationListener() {

            @Override
            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub
                LATITUDE = location.getLatitude();
                LONGITUDE = location.getLongitude();
                alm.removeUpdates(this);
                // alm.setTestProviderEnabled(provider, false);
            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub

            }

        };

        // 加载Position对象,对其附上经纬值
        String tempString = "javascript:var Position = function(latitude, longitude) {this._latitude ="
                .concat(String.valueOf(LATITUDE))
                .concat("; this.__defineGetter__(\"latitude\", function(){return this._latitude;}); this.__defineSetter__(\"latitude\", function(cn){throw {message: \"Cannot modify the const attribute\"};});  this._longitude =")
                .concat(String.valueOf(LONGITUDE))
                .concat("; this.__defineGetter__(\"longitude\", function(){return this._latitude;}); this.__defineSetter__(\"longitude\", function(cn){throw {message: \"Cannot modify the const attribute\"};}); };");
        ewv.loadUrl(tempString);
        Utils.printOutToConsole(tempString);
        callbackString = "javascript:".concat(Callback).concat("(0, Position)");
        ewv.loadUrl(callbackString);
        Utils.printOutToConsole(callbackString);
    }
}
